package com.zyf.connotation.fragment

import android.app.ActivityOptions
import android.content.Intent
import android.support.design.widget.FloatingActionButton
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.AnimationSet
import android.view.animation.RotateAnimation
import android.widget.AbsListView
import android.widget.Toast
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.zyf.connotation.BaseFragment
import com.zyf.connotation.R
import com.zyf.connotation.bean.Connotation
import com.zyf.connotation.presenter.ConnotationPresenter
import com.zyf.connotation.ui.ConnotationInfoActivity
import com.zyf.connotation.utils.DensityUtils
import com.zyf.connotation.utils.ShardUtil
import com.zyf.connotation.view_interface.IConnotationView
import fm.jiecao.jcvideoplayer_lib.JCMediaManager
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerManager
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard
import kotlinx.android.synthetic.main.connotation_fragment.view.*
import kotlinx.android.synthetic.main.rec_item.view.*
import java.util.*

/**
 * 作者：Think
 * 创建于 2017/5/31 17:00
 */
class VideoConnatationFragment :BaseFragment(), IConnotationView {

    var swipe: SwipeRefreshLayout?=null
    var recycle: RecyclerView?= null
    var animationSet: AnimationSet? = null
    var float_btn: FloatingActionButton? =null
    var floatBthRefresh = false
    var mLayoutInflater:LayoutInflater? = null
    var presenter: ConnotationPresenter = ConnotationPresenter(this)
    var connotationAdapter:ConnotationAdapter? = null
    var allData: ArrayList<Connotation.Data> = ArrayList()
    var pos = 0
    private var record = 0
    override fun initView(inflater: LayoutInflater?, container: ViewGroup?): View? {
        return inflater?.inflate(R.layout.connotation_fragment,container,false)
    }

    override fun initFindViewById(view: View?) {
        mLayoutInflater = LayoutInflater.from(baseActivity!!)
        swipe = view?.swipe
        recycle = view?.recycle
        float_btn = view?.float_btn
        swipe?.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light)
        swipe?.setOnRefreshListener {
            netData(true)
        }
        recycle?.layoutManager = LinearLayoutManager(baseActivity)
        recycle?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                val layoutManager = recyclerView!!.layoutManager as LinearLayoutManager
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()
                //当前屏幕所看到的子项个数
                val visibleItemCount = layoutManager.childCount
                //当前RecyclerView的所有子项个数
                val totalItemCount = layoutManager.itemCount
                //RecyclerView的滑动状态
                when (newState) {
                    AbsListView.OnScrollListener.SCROLL_STATE_IDLE -> if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 ) {
                        netData(false)
                    }
                }
                val lastItemPosition = layoutManager.findLastVisibleItemPosition()
                //获取第一个可见view的位置
                val firstItemPosition = layoutManager.findFirstVisibleItemPosition()
                if(pos<firstItemPosition||pos>lastItemPosition){
                    JCVideoPlayer.releaseAllVideos()
                }
                super.onScrollStateChanged(recyclerView, newState)
            }
        })
        animationSet = AnimationSet(true)
        var rotate = RotateAnimation(0f,360f, Animation.RELATIVE_TO_SELF,0.5f, Animation.RELATIVE_TO_SELF,0.5f)
        rotate.duration = 1000
        rotate.repeatCount = -1
        animationSet?.addAnimation(rotate)
        float_btn?.setOnClickListener {
            if(!floatBthRefresh){
                swipe?.setProgressViewOffset(false, 0, 48)
                swipe?.isRefreshing = true
                recycle?.scrollToPosition(0)
                netData(true)
            }
        }
        var data = ShardUtil.getPreferenceString(activity,"video")
        if(!TextUtils.isEmpty(data)){
            allData.addAll(Gson().fromJson<ArrayList<Connotation.Data>>(data,object: TypeToken<ArrayList<Connotation.Data>>(){}.type))
        }
        connotationAdapter = ConnotationAdapter()
        recycle?.adapter = connotationAdapter
    }
    inner class ConnotationAdapter:RecyclerView.Adapter<ConnotationHolder>(){
        override fun getItemCount(): Int {
            return allData.size
        }

        override fun onBindViewHolder(holder:ConnotationHolder, position: Int) {
            var data = allData[position]
            if(data.group?.is_anonymous!=null&&data.group?.is_anonymous){
                holder.anonymous?.visibility = View.VISIBLE
                holder.user_layout?.visibility = View.GONE
            }else{
                holder.anonymous?.visibility = View.GONE
                holder.user_layout?.visibility = View.VISIBLE
                holder.username?.text = data.group.user.name
                holder.head_img?.setImageURI(data.group.user.avatar_url)
            }
            if(record>0&&record-position == 1){
                holder.line?.visibility = View.GONE
            }else{
                holder.line?.visibility = View.VISIBLE
            }
            if( record>0&&record == position){
                //TODO
                holder.record_ll?.visibility = View.VISIBLE
                holder.record_ll?.setOnClickListener {
                    swipe?.setProgressViewOffset(false, 0, 48)
                    swipe?.isRefreshing = true
                    recycle?.scrollToPosition(0)
                    netData(true)
                }
            }else{
                holder.record_ll?.visibility = View.GONE
            }
            if(data.group.is_neihan_hot) holder.hot?.visibility = View.VISIBLE else holder.hot?.visibility = View.INVISIBLE

            holder.content?.text = data.group.content
            if(TextUtils.isEmpty(data.group.content)){
                holder.content?.visibility = View.GONE
            }
            var linearParams = holder.videoplayer?.layoutParams //取控件textView当前的布局参数 linearParams.height = 20;// 控件的高强制设成20
            if(data.group.video_height>480){
                linearParams?.height = DensityUtils.dpToPx(400F).toInt()
                holder.videoplayer?.widthRatio = 4
                holder.videoplayer?.heightRatio = 3
            }else{
                linearParams?.height = DensityUtils.dpToPx(200F).toInt()
                holder.videoplayer?.widthRatio = 16
                holder.videoplayer?.heightRatio = 9
            }
            holder.videoplayer?.layoutParams = linearParams  //使设置好的布局参数应用到控件
            holder.videoplayer?.measure(0,0)
            holder.videoplayer?.setUp(data.group.mp4_url, JCVideoPlayerStandard.SCREEN_LAYOUT_LIST,"")
            Glide.with(baseActivity).load(data.group.large_cover.url_list[0].url).into(holder.videoplayer?.thumbImageView)
            holder.videoplayer?.setPos(position)
            holder.videoplayer?.setPlayListener {
                pos = it
            }
            holder.category_name?.text = data.group.category_name
            holder.fabulous?.text = ""+data.group.digg_count
            if(data.group.user_digg == 1){
                holder.fabulous_image?.setImageResource(R.drawable.fabulous)
                holder.fabulous?.setTextColor(resources.getColor(R.color.textColor))
            }else{
                holder.fabulous_image?.setImageResource(R.drawable.no_fabulous)
                holder.fabulous?.setTextColor(resources.getColor(R.color.noColor))
            }
            holder.stampede?.text = ""+data.group.bury_count
            if(data.group.user_bury == 1){
                holder.stampede_image?.setImageResource(R.drawable.stampede)
                holder.stampede?.setTextColor(resources.getColor(R.color.textColor))
            }else{
                holder.stampede_image?.setImageResource(R.drawable.no_stampede)
                holder.stampede?.setTextColor(resources.getColor(R.color.noColor))
            }
            holder.message?.text = ""+data.group.comment_count
            holder.fabulous_layout?.setOnClickListener {
                if(data.group.user_digg ==1||data.group.user_bury ==1){
                    Toast.makeText(this@VideoConnatationFragment.baseActivity,"您已经顶过", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }else{
                    holder.fabulous_image?.setImageResource(R.drawable.fabulous)
                    holder.fabulous?.setTextColor(resources.getColor(R.color.textColor))
                    holder.fabulous?.text = ""+(data.group.digg_count+1)
                    data.group.user_digg = 1
                }
                presenter.netFabulous(position,"digg",data)
            }
            holder.stampede_layout?.setOnClickListener {
                if(data.group.user_digg ==1||data.group.user_bury ==1){
                    Toast.makeText(this@VideoConnatationFragment.baseActivity,"您已经顶过", Toast.LENGTH_SHORT).show()
                    return@setOnClickListener
                }else{
                    holder.stampede_image?.setImageResource(R.drawable.stampede)
                    holder.stampede?.setTextColor(resources.getColor(R.color.textColor))
                    holder.stampede?.text = ""+(data.group.bury_count+1)
                    data.group.user_bury =1
                }
                presenter.netFabulous(position,"bury",data)
            }
            holder.view?.setOnClickListener {
                var play = false
                try {
                    play = JCMediaManager.instance().mediaPlayer.isPlaying
                } catch(e: Exception) {
                    play = false
                }
                var url = ""
                if(JCVideoPlayerManager.getCurrentJcvd()!=null){
                    url = JCVideoPlayerManager.getCurrentJcvd().url
                }
                var intent = Intent(this@VideoConnatationFragment.baseActivity, ConnotationInfoActivity::class.java)
                intent.putExtra("data",data)
                intent.putExtra("url",url)
                intent.putExtra("play",play)
                if (android.os.Build.VERSION.SDK_INT > 20)
                    startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(this@VideoConnatationFragment.baseActivity,holder.view,"conntation").toBundle())
                else
                    startActivity(intent)
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ConnotationHolder {
            return ConnotationHolder(mLayoutInflater?.inflate(R.layout.rec_item, parent, false))
        }
    }
    inner class ConnotationHolder(itemView: View?): RecyclerView.ViewHolder(itemView){
        var view = itemView
        var hot = itemView?.hot
        var head_img = itemView?.head_img
        var username = itemView?.name
        var content = itemView?.content
        var category_name = itemView?.category_name
        var user_layout = itemView?.user_layout
        var anonymous = itemView?.anonymous
        var fabulous_image = itemView?.fabulous_image
        var fabulous = itemView?.fabulous
        var stampede_image = itemView?.stampede_image
        var stampede = itemView?.stampede
        var message = itemView?.message
        var fabulous_layout = itemView?.fabulous_layout
        var stampede_layout = itemView?.stampede_layout
        var record_ll = itemView?.record_ll
        var videoplayer = itemView?.videoplayer
        var line = itemView?.line
    }

    override fun initData() {
        if(allData.size!=0){
            return
        }
        swipe?.setProgressViewOffset(false, 0, 48)
        swipe?.isRefreshing = true
        presenter.getVideoList(Connotation::class.java,true)
    }
    override fun <T> DataList(t: T?,isTop:Boolean) {
        swipe?.isRefreshing = false
        floatBthRefresh = false
        float_btn?.clearAnimation()
        initData(t as Connotation,isTop)
    }

    override fun fabulous(position: Int, check: String) {
        //connotationAdapter?.notifyItemChanged(position)
    }
    fun netData(isTop:Boolean){
        floatBthRefresh = true
        float_btn?.startAnimation(animationSet)
        presenter.getVideoList(Connotation::class.java,isTop)
    }
    private fun initData(data:Connotation,istop: Boolean) {
        Toast.makeText(baseActivity,data.tip, Toast.LENGTH_SHORT).show()
        if(istop&&allData.size>100){
            var size = allData.size
            for(i in 0..20){
                allData.removeAt((size/2+10)-i)
            }
        }
        var i = 0
        data.data.forEach {
            if(it.type!=5){
                if(istop){
                    i++
                    allData.add(0,it)
                }else{
                    allData.add(it)
                }
            }
        }
        record = i
        connotationAdapter?.notifyDataSetChanged()
    }

    override fun onPause() {
        super.onPause()
        JCVideoPlayer.releaseAllVideos()
    }
    fun back():Boolean{
        if (JCVideoPlayer.backPress()) {
            return true
        }
        return false
    }

    override fun onDestroy() {
        ShardUtil.savePreferenceString(baseActivity!!,"video", Gson().toJson(allData))
        super.onDestroy()
    }
    override fun error(error: String) {
        Toast.makeText(this@VideoConnatationFragment.baseActivity,error,Toast.LENGTH_SHORT).show()
        swipe?.isRefreshing = false
    }
}